package com.yyfax.ph.personal.authority.login;

import android.text.TextUtils;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IEvent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.personal.authority.RSAPresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class LoginPresenter extends RSAPresenter<LoginModel, LoginPresenter.View> {
	private static final String TAG = LoginPresenter.class.getSimpleName();


	public static class Generator implements PresenterFactory<LoginPresenter> {
		@Override
		public LoginPresenter create() {
			return new LoginPresenter();
		}
	}

	private View mView;

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new LoginModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		void userLoginSuccess();

		void userLoginFailure(String tips);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		LoginModel.Login login = (LoginModel.Login) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		login.loginName = RSA.encryptByPublicKey(login.loginName, keyRSA);
		login.password = RSA.encryptByPublicKey(login.password, keyRSA);
		return login;
	}

	public void login(final String name, final String pwd) {
		final LoginModel.Login login = new LoginModel.Login(name, pwd);
		execute(login);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void loginResult(LoginModel.LoginResult result) {
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_E039, result.getStatus());
		CLog.i(TAG, "loginResult = " + result.toString());
		if (isResponseSuccess(result)) {
			LoginModel.LoginContentBean bean = result.getContent();
			YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_USER_ID, bean.id);
			YJPH.getInstance().onLoginSuccess(bean);//检查是否切换了账号
			EventAgent.postSticky(new IEvent.LoginSuccessEvent(IEvent.CODE_LOGIN_SUCCESS));
			mView.userLoginSuccess();
		} else {
			String tips = result.getMsg();
			mView.userLoginFailure(TextUtils.isEmpty(tips) ? "登录失败!" : tips);
		}
	}
}